package org.db.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import org.db.Manager;
import org.db.dao.ProjektDatenDAO;

/**
 * 
 * @author Lutz
 */
public class ProjektDatenDialog extends CloseCommitDialog
		implements
			ActionListener,
			DocumentListener,
			KeyListener {

	private static final long serialVersionUID = 1609377446755470804L;

	private static final String GleisanzahlException = "Die Gleisanzahl sollte mindestens 1 sein!";

	private javax.swing.JButton jButtonCancel;

	private javax.swing.JButton jButtonOK;

	private javax.swing.JLabel jLabel1;

	private javax.swing.JLabel jLabel2;

	private javax.swing.JLabel jLabel3;

	private javax.swing.JLabel jLabel4;

	private javax.swing.JLabel jLabel5;

	private javax.swing.JLabel jLabel6;

	private javax.swing.JLabel jLabel7;

	private javax.swing.JLabel jLabel8;

	private javax.swing.JScrollPane jScrollPane1;

	private javax.swing.JTextField jTextAuftragsNr;

	private IntegerTextField jTextGeschw;

	private javax.swing.JTextField jTextHoehenbezug;

	private javax.swing.JTextField jTextLagebezug;

	private javax.swing.JTextArea jTextProject;

	private IntegerTextField jTextGleis;

	public ProjektDatenDialog(JDialog owner) {
		super(owner);
		setTitle("Projekt anlegen");
		setModal(true);
		initComponents();
	}

	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();
		jTextAuftragsNr = new javax.swing.JTextField();
		jTextAuftragsNr.getDocument().addDocumentListener(this);
		jTextAuftragsNr.requestFocusInWindow();
		jLabel3 = new javax.swing.JLabel();
		jScrollPane1 = new javax.swing.JScrollPane();
		jTextProject = new javax.swing.JTextArea();
		jTextProject.getDocument().addDocumentListener(this);
		jLabel4 = new javax.swing.JLabel();
		jTextLagebezug = new javax.swing.JTextField();
		jTextLagebezug.getDocument().addDocumentListener(this);
		jLabel5 = new javax.swing.JLabel();
		jTextHoehenbezug = new javax.swing.JTextField();
		jTextHoehenbezug.getDocument().addDocumentListener(this);
		jButtonCancel = new javax.swing.JButton();
		jButtonOK = new javax.swing.JButton();
		jLabel6 = new javax.swing.JLabel();
		jTextGleis = new IntegerTextField();
		jTextGleis.getDocument().addDocumentListener(this);
		jLabel7 = new javax.swing.JLabel();
		jLabel8 = new javax.swing.JLabel();
		jTextGeschw = new IntegerTextField();
		jTextGeschw.getDocument().addDocumentListener(this);

		setResizable(false);

		jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
		jLabel1.setText("Projektdaten");

		jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel2.setText("Auftragsnummer");

		jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel3.setText("Projektbeschreibung");

		jTextProject.setColumns(20);
		jTextProject.setRows(5);
		jScrollPane1.setViewportView(jTextProject);

		jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel4.setText("Koordinatensystem");

		jTextLagebezug.setToolTipText("z.B. 42/83");

		jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel5.setText("Höhensystem");

		jTextHoehenbezug.setToolTipText("z.B. HN76");

		jButtonCancel.setFont(new java.awt.Font("Tahoma", 1, 12));
		jButtonCancel.setText("Abbrechen");
		jButtonCancel
				.setToolTipText("Verwerfen der Eingaben. Zurück zum Hauptmenü.");
		jButtonCancel.addActionListener(this);
		jButtonCancel.addKeyListener(this);

		jButtonOK.setFont(new java.awt.Font("Tahoma", 1, 12));
		jButtonOK.setText("Fertig");
		jButtonOK.setEnabled(false);
		jButtonOK.setToolTipText("Prüfen und Speichern der Eingaben.");
		jButtonOK.addActionListener(this);
		jButtonOK.addKeyListener(this);

		jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel6.setText("Anzahl der Gleise");

		jTextGeschw.setToolTipText("z.B. 200km/h");

		jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel7.setText("Hg/Ve");

		jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel8.setText("km/h");

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jLabel1)
												.addGroup(
														layout.createSequentialGroup()
																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.TRAILING)
																				.addComponent(
																						jLabel7)
																				.addComponent(
																						jLabel6)
																				.addComponent(
																						jLabel4)
																				.addComponent(
																						jLabel3)
																				.addComponent(
																						jLabel2)
																				.addComponent(
																						jLabel5))
																.addPreferredGap(
																		javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.LEADING)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										jTextHoehenbezug,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										85,
																										javax.swing.GroupLayout.PREFERRED_SIZE)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																										322,
																										Short.MAX_VALUE)
																								.addComponent(
																										jButtonOK,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										109,
																										javax.swing.GroupLayout.PREFERRED_SIZE)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										jButtonCancel,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										109,
																										javax.swing.GroupLayout.PREFERRED_SIZE))
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										jTextLagebezug,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										85,
																										javax.swing.GroupLayout.PREFERRED_SIZE)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																										546,
																										Short.MAX_VALUE))
																				.addComponent(
																						jScrollPane1,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						275,
																						javax.swing.GroupLayout.PREFERRED_SIZE)
																				.addComponent(
																						jTextAuftragsNr,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						88,
																						javax.swing.GroupLayout.PREFERRED_SIZE)
																				.addComponent(
																						jTextGleis,
																						javax.swing.GroupLayout.PREFERRED_SIZE,
																						32,
																						javax.swing.GroupLayout.PREFERRED_SIZE)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										jTextGeschw,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										55,
																										javax.swing.GroupLayout.PREFERRED_SIZE)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										jLabel8)))))
								.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jLabel1)
								.addGap(52, 52, 52)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel2)
												.addComponent(
														jTextAuftragsNr,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addGap(18, 18, 18)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jLabel3)
												.addComponent(
														jScrollPane1,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														67,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addGap(15, 15, 15)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(
														jTextGeschw,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jLabel7)
												.addComponent(jLabel8))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(
														jTextGleis,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jLabel6))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED,
										32, Short.MAX_VALUE)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(
														jTextLagebezug,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jLabel4))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel5)
												.addComponent(
														jTextHoehenbezug,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(
														jButtonCancel,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														33,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(
														jButtonOK,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														33,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addGap(39, 39, 39)));
		pack();
		setLocationRelativeTo(null);
		fillFields();
	}

	/**
	 * Laden der Textfelder, falls Projektdaten vorhanden
	 */
	private void fillFields() {
		ProjektDatenDAO projekt = Manager.getInstance().getProjekt();
		if (projekt != null) {
			jTextAuftragsNr.setText(projekt.getAuftragsNr());
			jTextProject.setText(projekt.getProjektBeschreibung());
			jTextGleis.setText(String.valueOf(projekt.getGleisAnzahl()));
			jTextGeschw.setText(String.valueOf(projekt.getGeschwindigkeit()));
			jTextHoehenbezug.setText(projekt.getHoehensystem());
			jTextLagebezug.setText(projekt.getKoordinatensystem());
		}
	}

	public int showDialog() {
		setVisible(true);
		return returnValue;
	}

	/**
	 * Prüfen ob Pflichtfelder gefüllt sind
	 */
	private boolean allInputElementsNotEmpty() {
		return !jTextAuftragsNr.getText().isEmpty()
				&& !jTextProject.getText().isEmpty()
				&& !jTextGleis.getText().isEmpty()
				&& !jTextGeschw.getText().isEmpty();
	}

	private void validateInput() {
		jButtonOK.setEnabled(allInputElementsNotEmpty());
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == jButtonOK) {
			if (isCheckInput()) {
				String auftragsnummer = jTextAuftragsNr.getText();
				// falls das Projekt bereits existiert fragen ob die Daten
				// geladen werden sollen
				if (!Manager.getInstance().projektLoaded(auftragsnummer)
						&& Manager.getInstance().projektExists(auftragsnummer)) {
					int ret = JOptionPane.showConfirmDialog(this,
							getProjektExistsMessage(jTextAuftragsNr.getText()),
							"Projekt bereits vorhanden",
							JOptionPane.YES_NO_OPTION);
					if (ret == JOptionPane.YES_OPTION) {
						close();
						Manager.getInstance().loadExistingProjekt(
								auftragsnummer);
						final ProjektDatenDialog projektDialog = new ProjektDatenDialog(
								this);

						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								int returnValue = projektDialog.showDialog();
								if (returnValue == JOptionPane.OK_OPTION) {
									final AuswahlDialog auswahlDialog = new AuswahlDialog(
											(JDialog) getOwner());
									auswahlDialog.setLocationRelativeTo(null);
									auswahlDialog.setVisible(true);
								}
							}
						});
					}
				} else {// sonst neu anlegen
					returnValue = JOptionPane.OK_OPTION;
					int gleisAnzahl = Integer.valueOf(jTextGleis.getText());
					GleisDefinitionDialog gleisDefinitionsDialog = new GleisDefinitionDialog(
							this, gleisAnzahl);
					int ret = gleisDefinitionsDialog.showDialog();
					if (ret == JOptionPane.OK_OPTION) {
						String projektBeschreibung = jTextProject.getText();
						String koordinatensystem = jTextLagebezug.getText();
						String hoehensystem = jTextHoehenbezug.getText();
						int geschwindigkeit = Integer.valueOf(jTextGeschw
								.getText());

						ProjektDatenDAO dao = new ProjektDatenDAO(
								auftragsnummer, projektBeschreibung,
								gleisAnzahl, geschwindigkeit,
								koordinatensystem, hoehensystem);

						Manager.getInstance().setProjekt(dao);
						// Manager.getInstance().commit();
						Manager.getInstance().applyChanges();
						close();
					}

				}

			}

		} else if (e.getSource() == jButtonCancel) {
			returnValue = JOptionPane.CANCEL_OPTION;
			askForClosing();
		}

	}

	/**
	 * Gleisanzahl mindestens 1
	 */
	private boolean isCheckInput() {
		Integer gleis = jTextGleis.getValue();
		if (gleis <= 0) {
			JOptionPane.showMessageDialog(this, GleisanzahlException,
					"Gleisanzahl", JOptionPane.WARNING_MESSAGE);
			return false;
		}
		return true;
	}

	private String getProjektExistsMessage(String auftragsnummer) {
		return "Ein Projekt mit der Auftragsnummer "
				+ auftragsnummer
				+ " ist bereits vorhanden.\n Möchten Sie das Projekt jetzt laden?";
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		validateInput();

	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		validateInput();

	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		validateInput();

	}

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getSource() == jButtonCancel) {
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				jButtonCancel.doClick();
			}
		} else if (e.getSource() == jButtonOK) {
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				jButtonOK.doClick();
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {

	}

	@Override
	public void keyTyped(KeyEvent arg0) {

	}

}
